package servlet;

import model.Blog;
import model.BlogDao;
import model.User;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2022-03-10
 * Time:21:51
 */
//此处的这个servletpath 是可以带后缀的，加了这个 .html,前端可以完全不关注，这个东西是静态页面还是动态页面
    @WebServlet("/blog_list")
public class BlogListServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        User user = Util.checkLogin(req);
        if (user == null){
//            如果当前未登录,就直接重定向到登录页面
            System.out.println("当前未登录不能访问博客列表页！");
            resp.sendRedirect("blog_login.html");
            return;
        }
        //        先从数据库中查询到博客列表
        BlogDao blogDao = new BlogDao();
        List<Blog> blogs = blogDao.selectAll();
        TemplateEngine engine =(TemplateEngine) getServletContext().getAttribute("engine");
//        通过模板引擎替换
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("blogs",blogs);
        webContext.setVariable("user",user);
        engine.process("blog_list",webContext,resp.getWriter());
    }
}
